<template>
  <div class='common-from'>
    <van-cell-group v-for="(item,index) in modelData" :key="index">
      <van-field v-if="item.type=='input'" v-model="$store.state.formData[item.prop]" input-align='right' :type="item.dataType||'input'" :label="item.label" :placeholder="item.placeholder" :readonly="item.readonly" />
      <p class="select" v-else-if="item.type==='select'||item.type==='datetime'" @click="showAcheet(item)"><span>{{item.label}}</span><span class="fr">{{item.value||$store.state.formData[item.prop]||item.placeholder}}</span></p>
      
      <div class="textarea-box" v-else-if="item.type=='textarea'">
        <p>{{item.label}}</p>
        <van-field  v-model="$store.state.formData[item.prop]" :type="item.dataType" :placeholder="item.placeholder" />
      </div>

      <div class="is-add" v-else-if="item.type==='is-add'">
        <itemModel :modelData="item.addModel" :addKey="item.prop" />
      </div>

      <div class="is-switch select pr" v-else-if="item.type==='switch'">
        <span>{{item.label}}</span>
        <van-switch v-model="item.value" @change="setSwitch(item)" />
      </div>

      <div class="is-router select" v-else-if="item.type=='router'" @click="myClick(item)">
        <span>{{item.label}}</span>
        <span class="fr">{{$store.state.dias.studentSelect.selectedNumber.length>0?$store.state.dias.studentSelect.selectedNumber.length+"人":item.label}}</span>
      </div>

      <div class="is-label select bc-gray" v-else-if="item.type=='label'">
        <span>{{item.label}}</span>
      </div>

      <div class="is-label select label-btns" v-else-if="item.type=='label-btns'">
        <span>{{item.label}}</span>
        <span v-for="(btn, btnindex) in item.btns" :key="btnindex" v-show="btn.show" :class="btn.class" @click="operateForm(item,btn)">{{btn.label}}</span>
      </div>

      <div class="margin bc-gray" v-else-if="item.type==='is-margin'"></div>

    </van-cell-group>
    <p class="notice" v-if="showNotice">注意哦: <span v-for="(not, index) in noticeInfo" :class="{'color-red':index==1}" :key="index">{{not}}</span></p>
    <van-button type="primary" @click="save" class="bc-green btn-sure">确定</van-button>

    <p style="display:none">{{getModelData}}</p>
  </div>
</template>
<script>
import MixIns from '../../mixin/mixin.js'
import FormListData from "./formdata.js";
import itemModel from './add/add'
export default {
  props:["model_Data"],
  components: {itemModel},
  name: "",
  data() {
    return {
      modelData: [],
      acheetInfo:{}, //暂时保存的下拉数据
      roomList:[],
      showNotice:false,
      noticeInfo:[]
    };
  },
  computed:{
    getModelData(){
      if(this.model_Data)this.modelData=this.model_Data
    }
  },
  methods: {
    /**
     * @name 添加 取消 表单
     */
    operateForm(item,btn){
      item.btns.forEach(ele=>ele.show=true)
      this.$set(btn,"show",false)
      this.$set(item,"showForm",!item.showForm)

      let index2 = this.modelData.slice(6).findIndex(val=>val.type=='is-margin')
      if(!item.showForm&&index2>-1){
        this.modelData.splice(5,index2+2)
      }else if(item.showForm){
        this.$store.state.formData.posts=[{form_content:""}]
        this.modelData.splice(5,0,
          {type:"is-margin"},
          {prop:"form_title",label:"表单标题",placeholder:"请输入标题",type:"input",},
          {
            type:'is-add',
            prop:'posts',
            addModel:[
              [
                {prop:"form_content",label:"字段内容",placeholder:"请输入字段内容",type:"input",check:false},
              ]
            ]
          },
          {type:"is-margin"}
        )
      }
    },
    myClick(item){
      if(typeof item.click ==="string"){
        this[item.click]()
      }else{
        item.click()
      }
    },
    /**
     * @name init 初始化
     */
    myinit() {
      this.$store.state.formData={}
      var result=this.model_Data||this.modelData
      FormListData.forEach(val => {
        if (val.key === _router.history.current.path) {
          this.$set(this, "modelData", JSON.parse(JSON.stringify(val.data)));
          result=this.model_Data||this.modelData
        }
      });
      // 生成模板数据
      result.forEach(ele => {
        if(ele.type=='is-add'){
          var obj={}
          if(ele.addModel){
            ele.addModel[0].forEach(ele1=>{
              if(ele1.prop)obj[ele1.prop]=""
            })
          }
          this.$store.state.formData[ele.prop]=ele.isMultiImg?['']:[obj]
        }else{
          this.$store.state.formData[ele.prop] = ele.value||"";
        }
      });
    },

    save(){
      if(this.checkParams(this.modelData,this.$store.state.formData)){
        const path = _router.history.current.path
        if(path!=="/attendance/sign/addSign"){
          _g.apiPost(this.resquest.add||this.resquest.edit,this.ArrayToJson(this.$store.state.formData)).then(res=>{
            _g.toMessage(res)
            if(!res.error)this.$router.go(-1)
          })
        }else{
          // 特殊的签到保存
          _g.apiPost(this.resquest.add,this.ArrayToJson(this.$store.state.formData)).then(res=>{
            _g.toMessage(res)
            if(!res.error)this.$router.push("/attendance/sign/signDetail/"+res.id)
          })
        }
        
      }
    },

    /**
     * @name 数组转化未json
     */
    ArrayToJson(obj){
      var params = JSON.parse(JSON.stringify(obj))
      for(var key in params){
        if(Array.isArray(params[key])){
          params[key]=JSON.stringify(params[key])
        }
      }
      return this.handleParams(params)
    },

    /**
     * @name 修改数据格式
     */
    handleParams(params){
      switch(_g.getRouterPath(this)){
        case "/lifeServe/rating/add":params.endtime=params.date+" "+params.time;params.maximum=params.limit||1;break;
        case "/jobServe/recruit/add":params.time=params.date+" "+params.time;params.type=2;break;
        case "/jobServe/preach/school/add":params.time=params.date+" "+params.time;params.type=1;break;
        case "/studyServe/exam/add":params.url=JSON.parse(params.url).slice(0,-1).join(",");break;
        case "/studyServe/research/notice/add":params.category=this.selectData.data1.find(val=>val.name==params.category).id ;break;
        case "/studyServe/research/order/add":params.category=this.selectData.data1.find(val=>val.name==params.category).id ;break;
        case "/workflow/input/punish/add":params.imgurl=JSON.parse(params.imgurl).slice(0,-1).join(",");break;
        case "/attendance/sign/addSign":
            params.category=["课程考勤","晚点名考勤","宿舍考勤","会议讲座考勤","其他考勤"].indexOf(params.category)-0+1;
            params.type=1
            params.scene=params.scene==="手持"?1:2
            if(params.category<3&&params.group)params.class_id=this.selectData.data1.find(val=>val.name==params.group).id
            if(params.category<3&&params.group)params.class_name=this.selectData.data1.find(val=>val.name==params.group).name
            if(params.classroom)params.classroom=this.selectData.data2.classroom.find(ele=>ele.classroom==params.classroom).id

            if(params.category>1)params.student_number=this.$store.state.dias.studentSelect.selectedNumber.join(",")
            delete params.group
            delete params.name
            if(params.category==3){
              delete params.scene
              params.type=3
              params.start_time=new Date(params.date+" "+params.start_time).getTime()/1000
              params.end_time=new Date(params.date+" "+params.end_time).getTime()/1000
              delete params.date
            }
            break;
        case "/message/1/add":
              params.imgUrl=JSON.parse(params.imgUrl).join();
              let formtitle = params.form_title;
              let formcontent = JSON.parse(params.posts)
              if(formtitle&&this.modelData[4].showForm){
                params.form[formtitle]=formcontent.map(val=>val.form_content).join();
              }
              params.receive=this.$store.state.dias.studentSelect.selectedNumber.join()
              delete params.form_title
              delete params.posts
              delete params.undefined
              break;
      }
      return params
    },

    /**
     * @name 检查参数
     */
    checkParams(rules,data){
      for(var i = 0;i<rules.length;i++){
        if(rules[i].check&&!data[rules[i].prop]){
          _g.toMessage({error:1,msg:rules[i].label+"不能为空"})
          return false
        }
      }
      return true
    },

    /**
     * @name 显示弹框(下拉)
     */
    showAcheet(item){
      if(item.type=='select'){
        this.acheetInfo=item
        this.$store.state.dias.acheet.columns=item.useReq?this.selectData.data1.map(val=>val[item.columnsKey?item.columnsKey:"name"]):item.columns
        this.$store.state.dias.acheet.confirm=this.confirmSelect
        this.$store.state.dias.acheet.show=true
      }else if(item.type=='datetime'){
        this.acheetInfo=item
        this.$store.state.dias.datetime.confirm=this.confirmDateTime
        this.$store.state.dias.datetime[item.dataType+"Show"]=true
      }
    },
    /**
     * @name 普通下拉确认
     */
    confirmSelect(val){
      this.$set(this.$store.state.formData,this.acheetInfo.prop,val)
      this.acheetInfo.value=val
      const path = _router.history.current.path
      if(path==="/attendance/sign/addSign"){
        if(this.acheetInfo.prop=='category')this.selectTogether1(val)
        if(this.acheetInfo.prop=='scene')this.selectTogether2(val)
        if(this.acheetInfo.prop=='name')this.selectTogether3(val)
      }else if(path==="/message/1/add"){
        if(this.acheetInfo.prop=='classify')this.selectTogether4(val)
      }
      
      this.$store.state.dias.acheet.show=false
    },
    /**
     * @name 签到 下拉联动1
     */
    selectTogether1(val){
      const path = _router.history.current.path
      this.$store.state.formData.type=val==="宿舍考勤"?"照片签到":"蓝牙签到";
      this.showNotice=val=="宿舍考勤"||val=="课程考勤"
      if(val=="宿舍考勤")this.noticeInfo=["开始时间和结束时间间隔不超过","4小时"]
      if(val=="课程考勤")this.noticeInfo=["课程考勤请先创建课程分组"]
      if(val=="课程考勤"||val=="晚点名考勤"){
        this.modelData=[
          {prop:"category",label:"签到主题",placeholder:"请选择签到主题",type:"select",check:true,value:"",columns:["课程考勤","晚点名考勤","宿舍考勤","会议讲座考勤","其他考勤"]},
          {prop:"type",label:"签到方式",placeholder:"签到方式",type:"input",readonly:true},
          {prop:"scene",label:"签到场景",placeholder:"请选择签到场景",type:"select",check:true,value:"",columns:["手持","教室"]},
          {prop:"comments",label:"备注",placeholder:"请输入备注",type:"input",check:false},
          val=="课程考勤"?{prop:"group",label:"课程分组",placeholder:"请选择课程分组",type:"select",check:true,value:"",columns:[],useReq:true}:{label:"签到对象",type:"router",click:this.chooseStu},
        ]
      }else if(val=="宿舍考勤"){
        this.modelData=[
          {prop:"category",label:"签到主题",placeholder:"请选择签到主题",type:"select",check:true,value:"",columns:["课程考勤","晚点名考勤","宿舍考勤","会议讲座考勤","其他考勤"]},
          {prop:"type",label:"签到方式",placeholder:"签到方式",type:"input",readonly:true},
          {prop:"comments",label:"口令",placeholder:"请输入口令",type:"input",check:true},
          {prop:"date",label:"签到日期",value:"",placeholder:"选择签到日期",type:"datetime",dataType:'date',check:true},
          {prop:"start_time",label:"开始时间",value:"",placeholder:"选择开始时间",type:"datetime",dataType:'time',check:true},
          {prop:"end_time",label:"结束时间",value:"",placeholder:"选择结束时间",type:"datetime",dataType:'time',check:true},

          val=="课程考勤"?{prop:"group",label:"课程分组",placeholder:"请选择课程分组",type:"select",check:true,value:"",columns:[],useReq:true}:{label:"签到对象",type:"router",click:this.chooseStu},
        ]
      }else if(val=="会议讲座考勤"||val=="其他考勤"){
        this.modelData=[
          {prop:"category",label:"签到主题",placeholder:"请选择签到主题",type:"select",check:true,value:"",columns:["课程考勤","晚点名考勤","宿舍考勤","会议讲座考勤","其他考勤"]},
          {prop:"type",label:"签到方式",placeholder:"签到方式",type:"input",readonly:true},
          {prop:"title",label:"主题",placeholder:"请输入主题",type:"input",check:true},
          {prop:"scene",label:"签到场景",placeholder:"请选择签到场景",type:"select",check:true,value:"",columns:["手持","教室"]},
          {prop:"comments",label:"备注",placeholder:"请输入备注",type:"input",check:false},
          val=="课程考勤"?{prop:"group",label:"课程分组",placeholder:"请选择课程分组",type:"select",check:true,value:"",columns:[],useReq:true}:{label:"签到对象",type:"router",click:this.chooseStu2},
        ]
      }
    },
    /**
     * @name 签到 下拉联动2
     */
    selectTogether2(val){
      console.log(val)
      const path = _router.history.current.path
      switch(path){
        case "/attendance/sign/addSign":
            if(val=="教室"){
              this.modelData.splice(3,0,{prop:"name",label:"教学楼",placeholder:"选择教学楼",type:"select",value:"",columns:this.selectData.data2.building.map(val=>val.name)},{prop:"classroom",label:"教室",placeholder:"选择教室",type:"select",value:"",columns:this.roomList});
            }else if(val=="手持"&&this.modelData.length==7){
              this.modelData.splice(3,2)
            }
            break;
      }
    },

    /**
     *@name 签到 下拉联动3 
     */
    selectTogether3(val){
      if(this.acheetInfo.prop=="name"){
        const id = this.selectData.data2.building.find(ele=>ele.name==val).id
        var goal=[]
        this.selectData.data2.classroom.forEach(ele=>{
          if(ele.pid==id)goal.push(ele)
        })
        this.$set(this.modelData[4],"columns",goal.map(ele=>ele.classroom))
      }
    },

    selectTogether4(val){
      let label =this.modelData.slice(-1)[0].label
      console.log(label)
      if(val=="会议消息"&&label!=="地点"){
        this.modelData.push(
          {prop:"location",label:"地点",placeholder:"请输入地点",type:"input",},
        )
      }else if(val=="普通消息"&&label==="地点"){
        this.modelData=this.modelData.slice(0,-1)
      }
      
    },

    chooseStu(){
      console.log("开始选择对象")
      this.$store.state.dias.studentSelect.show=true
    },
    chooseStu2(){
      console.log("开始选择对象")
      this.$store.state.dias.anotherSelect.show=true
    },

    /**
     * @name 时间选择确认
     */
    confirmDateTime(val){
      this.$set(this.$store.state.formData,this.acheetInfo.prop,_g.formatTime(val,this.acheetInfo.dataType))
      this.acheetInfo.value=_g.formatTime(val,this.acheetInfo.dataType)
      this.$store.state.dias.datetime.dateShow=false
      this.$store.state.dias.datetime.timeShow=false
      this.$store.state.dias.datetime.datetimeShow=false
    },

    /**
     * @name 设置交换
     */
    setSwitch(item){
      this.$store.state.formData[item.prop]=item.value
    }
  },
  created() {
    this.myinit();
  },
  mixins:[MixIns]
};
</script>
<style lang="scss" scoped>
.common-from {
  height: 100%;
  overflow: auto;
  
  .btn-sure{
    width:90%;
    margin:120px 5%;
    font-size: 18px;
  }
  .select{
    padding: 20px 35px;
    height: 60px;
    line-height: 60px;
    color: #333;
    border-bottom: 1px solid #efeff4;
  }
  .textarea-box{
    
    p{
      padding: 20px 35px;
      height: 60px;
      line-height: 60px;
      color: #333;
      box-sizing: content-box;
      border-bottom: 1px solid #efeff4;
    }
  }
  .margin{
    margin-top: 20px;
  }
  .notice{
    padding: 20px 30px;
    font-size: 12px;
    color: #999;
  }
  .notice:before{
    content: "*";
    color: red;
  }
  .label-btns{
    font-size: 12px;
    color: #999;
  }
  
  .margin{
    height: 20px;
    margin-top: 0;
  }
}
.color-red{
  color: red!important;
}
</style>